package com.apes.framework.plugin.workflow.parser.model;

import com.apes.framework.plugin.esb.processor.mapping.Mapping;
import com.apes.framework.plugin.esb.processor.mapping.parser.model.Config;
import lombok.Data;
import org.springframework.util.LinkedCaseInsensitiveMap;

import java.util.Map;

/**
 * 功能：workflow元模型
 *
 * @author xul
 * @create 2018-06-30 14:28
 */
@Data
public class Workflow {
    private static Map<String, Workflow> workflows = new LinkedCaseInsensitiveMap();

    private String id;

    /**
     * 默认表单
     */
    private Form form;

    private Map<String, Node> nodes = new LinkedCaseInsensitiveMap();


    /**
     * 功能：增加workflow元模型
     *
     * @param processDefinitionKey
     * @param workflow
     */
    public static void addWorkflow(String processDefinitionKey, Workflow workflow) {
        workflows.put(processDefinitionKey, workflow);
    }

    /**
     * 功能：获取workflow元模型
     *
     * @param processDefinitionKey
     * @return workflow
     */
    public static Workflow getWorkflow(String processDefinitionKey) {
        Workflow workflow = workflows.get(processDefinitionKey);
        if (workflow == null) {
            throw new RuntimeException("流程： " + processDefinitionKey + " 没有配置！");
        }
        return workflow;
    }

    /**
     * 功能：获取流程开始节点
     *
     * @return node
     */
    public Node getStartNode() {
        return getNode("start");
    }

    /**
     * 功能：获取流程任务节点
     *
     * @return node
     */
    public Node getTaskNode(String taskDefinitionKey) {
        return getNode("task", taskDefinitionKey);
    }

    /**
     * 功能：获取流程结束节点
     *
     * @return node
     */
    public Node getEndNode() {
        return getNode("end");
    }

    private Node getNode(String nodeName) {
        try {
            return nodes.values().stream().filter(node -> node.getName().equalsIgnoreCase(nodeName)).findFirst().get();
        } catch (Exception e) {
            return null;
        }
    }

    private Node getNode(String nodeName, String nodeId) {
        try {
            return nodes.values().stream().filter(node -> node.getName().equalsIgnoreCase(nodeName) && node.getId().equalsIgnoreCase(nodeId)).findFirst().get();
        } catch (Exception e) {
            return null;
        }
    }

    public void addNode(String nodeId, Node node) {
        nodes.put(nodeId, node);
    }


}
